<?php

/**
 * Generator class
 *
 * @author Eugene I. Nezhuta
 */
class RCMS_Object_Generator_Generator {

/**
 * Generator view path
 *
 */
	const VIEW_PATH = 'application/views/scripts/generator';

	/**
	 * Seo varriable top. (Used to integrate code from Google for analitics, wmtools)
	 *
	 */
	const SEOVAR_TOP = 'top';

	/**
	 * Seo varriable bottom. (Used to integrate code from Google for analitics, wmtools)
	 *
	 */
	const SEOVAR_BOTTOM = 'bottom';

	/**
	 * Generator model
	 *
	 * @var RCMS_Object_Generator_GeneratorModel
	 */
	private $_model = null;

	/**
	 * Allows generator add linkks (Add/Edit) to generated content
	 *
	 * @var boolean
	 */
	private $_addLinks = true;

	/**
	 * Website path
	 *
	 * @var string
	 */
	private $_sitePath = '';

	/**
	 * Website url
	 *
	 * @var string
	 */
	private $_siteUrl = '';

	/**
	 * Generator view
	 *
	 * @var Zend_View
	 */
	private $_generatorView = null;

	/**
	 * Language Id (english, spanish, etc...)
	 *
	 * @var string
	 */
	private $_languageId = '';

	/**
	 * Constructor
	 *
	 * @param boolean $addLinks
	 */
	public function  __construct($addLinks = true, $pluginConfigData = null, $languageId = '') {
		$this->_languageId = ($languageId != '') ? $languageId : '';
		$this->_model = new RCMS_Object_Generator_GeneratorModel();
		$this->_addLinks = $addLinks;
		$this->_sitePath = unserialize(Zend_Registry::get('config'))->website->website->path;
		$this->_siteUrl = unserialize(Zend_Registry::get('config'))->website->website->url;
		$this->_generatorView = new Zend_View();
		$this->_generatorView->setScriptPath($this->_sitePath . self::VIEW_PATH);
		$this->_generatorView->websiteUrl = $this->_siteUrl;
	}

	/**
	 * Generate website main navigation menu
	 *
	 * @return string
	 */
	public function generateMainMenu($expanded = false, $pageData = array(), $takeDraft = true) {
		$categories = $this->_model->getMainMenuCategories($takeDraft);
		foreach($categories as $key => $category) {
			$categories[$key]['pages'] = $this->_model->getMainMenuCategoryPages($category['categoryId']);
			$pages = $categories[$key]['pages'];
			foreach ($pages as &$page) {
				$page['url'] = urldecode($page['url']);
			}

			$categories[$key]['pages'] = $pages;
		}
		$this->_generatorView->sitePages = $categories;
		$this->_generatorView->classCounter = 0;
		if($expanded) {
			foreach ($categories as $catPage) {
				$page = new RCMS_Object_Page_Page($pageData['id']);
				if($page->getIsCategory()) {
					$this->_generatorView->currCat = $page->getUrl();
				}
				else {
					$catPageId = $this->_model->getPageIdByCategoryId($page->getParentCategoryId());
					$catPage = new RCMS_Object_Page_Page($catPageId);
					$this->_generatorView->currCat = $catPage->getUrl();
				}

			}
			return $this->_generatorView->render('mainmenuext.phtml');
		}
		return $this->_generatorView->render('mainmenu.phtml');
	}


	/**
	 * Generate site secondary "static" menu
	 *
	 * @return string
	 */
	public function generateStaticMenu() {
		$staticMenuPages = $this->_model->getStaicMenuPages();
		$this->_generatorView->staticPages = $staticMenuPages;
		return $this->_generatorView->render('staticmenu.phtml');
	}

	/**
	 * Generate wright content for 'text' containers
	 *
	 * @param string $containerName
	 * @param array $oageData
	 * @return string
	 */
	public function generateContentContainer($containerName, $options, $pageData) {
		$replacedContent = "";
		$data = $this->_model->selectContainerTextData($containerName, $pageData['id']);
		if(!$this->_addLinks) {
			if($data['published']==0)
				return "";
		}
		if($data['published']==0) {
			$replacedContent.="<div class='border_red'>";
		}

		$replacedContent .= $data['value'];

		if($data['published']==0) {
			$replacedContent.="<p style='clear:both;'/></div>";
		}

		if($this->_addLinks) {
			if($data === null || !$data) {
				$replacedContent = '<a title="Click to edit content" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/addcontent/name/' . $containerName . '/pageId/' . $pageData['id'] . '/?TB_iframe=true&height=634&width=940\',\' \');" class="generator-links"><img alt="edit content" src="' . $this->_siteUrl . 'system/images/editadd.png" /></a>';
			}
			else {
				$replacedContent .= '<a title="Click to edit content" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/editcontent/id/'.$data['id_container'].'/?TB_iframe=true&height=634&width=940\',\' \');" class="generator-links"><img alt="edit content" src="' . $this->_siteUrl . 'system/images/editadd.png" /></a>';
			//$replacedContent .= sprintf("<a title=\"Click to edit content\" href=\"javascript:;\" onclick=\"tb_show('%s','%s','%s');\" class=\"generator-links\"><img alt=\"edit content\" src=\"%s\" /></a>", ' ', $this->_siteUrl . 'sys/backend_container/editcontent/id/'.$data['id_container'].'/?TB_iframe=true&height=600&width=940', ' ', $this->_siteUrl . 'system/images/editadd.png');
			}
		}
		return $replacedContent;

	}

	/**
	 * Generates content for static containers
	 *
	 * @param string $containerName
	 * @return string
	 */
	public function generateStaticContent($containerName) {
		$data = $this->_model->selectStaticContainerData($containerName);
		$replacedContent = $data['value'];
		if($this->_addLinks) {
			if($data === null || !$data) {
				$replacedContent = '<a title="Click to edit static content" href="javascript:;"  onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/addcontent/name/'.$containerName.'/type/2?TB_iframe=true&height=600&width=940\',\' \')"   class="generator-links"><img src="' . $this->_siteUrl . 'system/images/editadd-static-content.png" alt="edit static content" /></a>';
			}
			else {
				$replacedContent .= '<a title="Click to edit static content" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/editcontent/id/'.$data['id_container'].'/?TB_iframe=true&height=600&width=940\',\' \')" class="generator-links"><img src="' . $this->_siteUrl . 'system/images/editadd-static-content.png" alt="edit static content" /></a>';
			}
		}
		return $replacedContent;

	}

	public function generateStaticHeaderContent($containerName) {
		$data = $this->_model->selectStaticContainerData($containerName, RCMS_Object_Container_Container::C_TYPE_STATICHEADER);
		$replacedContent = $data['value'];
		if($this->_addLinks) {
			if($data === null || !$data) {
				$replacedContent = '<a title="Click to edit header" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/addheader/name/'.$containerName.'/type/5?TB_iframe=true&height=255&width=600\',\' \')" class="generator-links"><img src="' . $this->_siteUrl . 'system/images/editadd-static-header.png" alt="edit static header" /></a>';
			}
			else {
				$replacedContent .= '<a title="Click to edit header" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/editheader/id/'.$data['id_container'].'/?TB_iframe=true&height=255&width=600\',\' \')" class="generator-links"><img src="' . $this->_siteUrl . 'system/images/editadd-static-header.png" alt="edit static header" /></a>';
			}
		}
		return $replacedContent;
	}

	public function generateGoogleMap($containerName) {
		$data = $this->_model->selectStaticContainerData($containerName, RCMS_Object_Container_Container::C_TYPE_GOOGLEMAP);
		$replacedContent = $data['value'];
		if($this->_addLinks) {
			if($data === null || !$data) {
				$replacedContent = '<a title="Click to add google map" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/addgooglemap/name/'.$containerName.'/type/'.RCMS_Object_Container_Container::C_TYPE_GOOGLEMAP.'?TB_iframe=true&height=360&width=535\',\' \')" class="generator-links">Add Google Map Code</a>';
			}
			else {
				$replacedContent .= '<a title="Click to edit google map" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/editgooglemap/id/'.$data['id_container'].'/?TB_iframe=true&height=360&width=535\',\' \')" class="generator-links">Edit Google Map Code</a>';
			}
		}
		return $replacedContent;
	}

	/**
	 * Generate content for header container
	 *
	 * @param string $containerName
	 * @param array $pageData current page data
	 * @return string
	 */
	public function generateHeaderContent($containerName, $pageData) {
		$data = $this->_model->selectContainerTextData($containerName, $pageData['id'], RCMS_Object_Container_Container::C_TYPE_HEADER);
		$replacedContent = $data['value'];
		if($this->_addLinks) {
			if($data === null || !$data) {
				$replacedContent = '<a title="Click to edit header" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/addheader/name/'.$containerName.'/pageId/'.$pageData['id'].'/?TB_iframe=true&height=255&width=600\',\' \')" class="generator-links"><img src="' . $this->_siteUrl . 'system/images/editadd-header.png" alt="edit header" /></a>';
			}
			else {
				$replacedContent .= '<a title="Click to edit header" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/editheader/id/'.$data['id_container'].'/?TB_iframe=true&height=255&width=600\',\' \')" class="generator-links"><img src="' . $this->_siteUrl . 'system/images/editadd-header.png" alt="edit header" /></a>';
			}
		}
		return $replacedContent;
	}

	public function generateCodeContent($containerName, $pageData) {
		$data = $this->_model->selectContainerTextData($containerName, $pageData['id'], RCMS_Object_Container_Container::C_TYPE_CODE);
		if(preg_match('/^<script>.*/', $data['value'])) {
			$replacedContent = $data['value'];
		}
		else {
			$replacedContent = eval($data['value']);
		}
		if($this->_addLinks) {
			if($data === null || !$data) {
				$replacedContent = '<a title="Click to edit code" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/addcode/name/'.$containerName.'/pageId/'.$pageData['id'].'/?TB_iframe=true&height=460&width=600\',\' \')" class="generator-links"><img src="' . $this->_siteUrl . 'system/images/editadd-code.png" alt="edit code" /></a>';
			}
			else {
				$replacedContent .= '<a title="Click to edit code" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_container/editcode/id/'.$data['id_container'].'/?TB_iframe=true&height=460&width=600\',\' \')" class="generator-links"><img src="' . $this->_siteUrl . 'system/images/editadd-code.png" alt="edit code" /></a>';
			}
		}
		return $replacedContent;
	}

	/**
	 * Generate content for featured area
	 *
	 * @param string $name
	 * @param array $options container options
	 * @param array $pageData current page data
	 * @return string
	 */
	public function generateFeaturedAreaContent($name, $options, $pageData) {

		$page = new RCMS_Object_Page_Page($pageData['id']);
		$featuredArea = new RCMS_Object_FeaturedArea_FeaturedArea();
		$featuredArea = $featuredArea->_model->selectFeaturedAreaByName($name);
		if($featuredArea) {
			if(empty($options))
				$options[0]=0;
			if($featuredArea->id>0)
				$pages = $this->_model->getPagesListByFeaturedId($featuredArea->id,$page->getId(),$options[0]);
			$this->_generatorView->featuredAreaName = str_replace(" ", "-",strtolower($name));


			if(isset($options[1])) {
				foreach ($pages as &$page) {
					$page['description'] = $this->cutDescription($page['description'],$options[1]);
				}

			}
			if(isset($options[2]) && $options[2]== 'random') {
				shuffle($pages);
			}
			$this->_generatorView->featuredPagesList = $pages;
			if(!empty ($pages))
				return $this->_generatorView->render('featuredareapagelist.phtml');
			return "";
		}else {
			return "";
		}
	}

	/**
	 * Generate content for featured area with images
	 *
	 * @param string $name
	 * @param array $options container options
	 * @param array $pageData current page data
	 * @return string
	 */
	public function generateFeaturedAreaImgContent($name, $options, $pageData) {
		$addLink = "";
		if($this->_addLinks) {
			$addLink = '<a title="Order Pages" href="javascript:;" onclick="tb_show(\' \',\'' . $this->_siteUrl . 'sys/backend_featuredarea/orderfa/name/'.$name.'/?TB_iframe=true&height=600&width=600\',\' \')" class="generator-links">Order Pages</a>';
		}

		$page = new RCMS_Object_Page_Page($pageData['id']);
		$featuredArea = new RCMS_Object_FeaturedArea_FeaturedArea();
		$featuredArea = $featuredArea->_model->selectFeaturedAreaByName($name);
		if($featuredArea) {
			if(empty($options)) {
				$options[0] = 0;
			}
			if($featuredArea->id>0)
				$pages = $this->_model->getPagesListImagesByFeaturedId($featuredArea->id,$page->getId(),$options[0]);
			$this->_generatorView->featuredAreaName = str_replace(" ", "-",strtolower($name));

			if(isset($options[1])) {
				foreach ($pages as &$page) {
					$page['description'] = $this->cutDescription($page['description'],$options[1]);
				}

			}
			if(isset($options[2]) && $options[2]== 'random') {
				shuffle($pages);
			}

			$this->_generatorView->featuredPagesList = $pages;
			if(!empty ($pages)) {
				//return $this->_generatorView->render('featuredareapageimgagelist.phtml').$addLink;
				return $this->_generatorView->render('featuredareapageimgagelist.phtml');
			}
			return '';
		}
		return '';

	}

	/**
	 * Generate list of pages for specified category
	 *
	 * @param array $pageData
	 * @return string
	 */
	public function generatePagesList($pageData) {

		$page = new RCMS_Object_Page_Page($pageData['id']);
		$catId = ($page->getParentCategoryId() == 0) ? $page->getCategoryId() : $page->getParentCategoryId();
		$pages = $this->_model->getCategoryPagesList($catId);
		$this->_generatorView->categoryPagesList = $pages;
		return $this->_generatorView->render('catpageslist.phtml');
	}

	/**
	 * Generate categories list with images or not if scecified
	 *
	 * @param boolean $withImages
	 * @return string
	 */
	public function generateCategoriesList($withImages = false, $takeDraft = true) {
		$categories = $this->_model->getCategoriesList($takeDraft);
		$this->_generatorView->categoriesList = $categories;
		if($withImages) {
			return $this->_generatorView->render('catlistimg.phtml');
		}
		return $this->_generatorView->render('catlist.phtml');
	}

	/**
	 * Generate list of pages for specified category.
	 *
	 * Shows only pages images with page's short description
	 *
	 * @param array $pageData
	 * @return string
	 */
	public function generatePagesListImg($pageData) {
		$page = new RCMS_Object_Page_Page($pageData['id']);
		$catId = ($page->getParentCategoryId() == 0) ? $page->getCategoryId() : $page->getParentCategoryId();
		$pages = $this->_model->getCategoryPagesListImg($catId);
		$this->_generatorView->categoryPagesListImg = $pages;
		return $this->_generatorView->render('catpageslistimg.phtml');
	}


	/**
	 * Generate site map
	 *
	 * @param array $pageData
	 * @return string
	 */
	public function generateSiteMap($pageData) {
		$categories = $this->_model->getSiteMapCategories();
		$page404Id = $this->_model->get404PageId();
		foreach($categories as $key => $category) {
			$categories[$key]['pages'] = $this->_model->getSiteMapCategoryPages($category['categoryId']);
		}
		$this->_generatorView->siteMapPages = $categories;
		$this->_generatorView->newsFolder = $this->_model->getNewsFolder();
		return $this->_generatorView->render('sitemap.phtml');
	}

	/**
	 * Generate xml sitemap
	 *
	 * @param array $sitePages
	 */
	public function generateSiteMapXml($sitePages) {
		$this->_generatorView->pages = $sitePages;
		$this->_generatorView->websiteUrl = $this->_siteUrl;
		$this->_generatorView->newsFolder = $this->_model->getNewsFolder();
		$this->_generatorView->lastMod = date('c', time());
		$fileContent = $this->_generatorView->render('sitemapxml.phtml');
		RCMS_Tools_FilesystemTools::saveFile('sitemap.xml', $fileContent);
	}

	/**
	 * Generates 301 redirect for renamed pages and put it into htaccess file
	 *
	 * @param array $redirectTable
	 */
	public function generateRedirects($redirectTable) {
		$additionalRulesContent = '';
		try {
			$additionalRulesContent = RCMS_Tools_FilesystemTools::getFile($this->_sitePath . 'xrules');
		}
		catch (Exception $e) {
			$additionalRulesContent = false;
		}
		$parsedUrl = parse_url($this->_siteUrl);
		$this->_generatorView->siteDir = trim($parsedUrl['path'], '/');
		$this->_generatorView->redirectTable = $redirectTable;
		$this->_generatorView->websiteUrl = $this->_siteUrl;
		$this->_generatorView->additionalRules = $additionalRulesContent;
		$htaccess = $this->_generatorView->render('htaccess.phtml');
		RCMS_Tools_FilesystemTools::saveFile($this->_sitePath . '.htaccess', $htaccess);
	}

	/**
	 * Generate category name for {$categoru_name} variable
	 *
	 * @param integer $pageId
	 * @return string
	 */
	public function generateCategoryName($pageId) {
		$page = new RCMS_Object_Page_Page($pageId, true);
		$result = $page->getParentCategoryName();
		return $result['name'];
	}


	/**
	 * Generate related page variable's content
	 *
	 * @param integer $countKeywords amount of keywords to be the same
	 * @param array $options container options
	 * @param array $data current page data
	 * @param boolean $withImg generate content with images or not
	 * @return string
	 */
	public function generateRelatedPages($countKeywords, $options, $data, $withImg = false) {
		if(intval($countKeywords) == 0 || !isset($options[0]) || intval($options[0]) == 0) {
			return;
		}
		$relatedPagesIds = array();
		$currentPageKeywords = explode(",", $data['meta_keywords']);
		foreach ($currentPageKeywords as $key => $value) {
			$currentPageKeywords[$key] = trim($value);
		}
		if(count($currentPageKeywords) >= $countKeywords) {
			$limit = $options[0];
			$allKeyWordsAndIds = $this->_model->getAllPagesIdsAndKeywords($data['id']);
			foreach ($allKeyWordsAndIds as $idKeywords) {
				$idKeywords['keywords'] = explode(",", $idKeywords['keywords']);
				foreach ($idKeywords['keywords'] as $key => $value) {
					$idKeywords['keywords'][$key] = trim($value);
				}
				foreach ($currentPageKeywords as $keyword) {
					if(empty ($keyword)) {
						continue;
					}
					if(count(array_intersect($currentPageKeywords, $idKeywords['keywords'])) >= $countKeywords) {
						$relatedPagesIds[] = $idKeywords['id'];
					}
				}
			}
			$relatedPagesData = $this->_model->getRelatedPagesData($relatedPagesIds, $limit, $withImg);
			$this->_generatorView->relatedPagesData = $relatedPagesData;
		}
		else {
			$this->_generatorView->relatedPagesData = array();
		}
		$this->_generatorView->withImage = $withImg;
		return $this->_generatorView->render('related.phtml');
	}

	/**
	 * Generate comments block content
	 *
	 * @param string $containerName
	 * @param array $options
	 * @param array $pageData
	 * @param boolean $isLogged
	 * @return string
	 */
	public function generateComments($containerName, $options,$pageData,$isLogged) {
	//clearing page with captcha from the cache
		$captchaId = $this->generateCaptcha();
		$topic = (isset($options[0]))? $options[0] : "";
		$keyword = (isset($options[1]))? $options[1] : "";
		$countComments = (isset($options[2]))? $options[2] : 4;
		$publishedByDefault = (isset($options[3]))? $options[3] : 0;

		$containerData = $this->_model->selectContainerTextData($containerName, $pageData['id']);
		$commentsArray = $this->_model->selectCommenstByContainerId($containerData['id_container'],$isLogged);

		//October 8, 2009 at 2:41 pm
		foreach ($commentsArray as &$comment) {
			$comment['date'] = RCMS_Tools_Tools::proccessPublishingDateCommentsFromSql($comment['date']);
		}
		$this->_generatorView->requestedPage  = $pageData['url'].".html";
		$this->_generatorView->captchaId = $captchaId;
		$this->_generatorView->topic = $topic;
		$this->_generatorView->keyword = $keyword;
		$this->_generatorView->countComments = $countComments;
		$this->_generatorView->publishedByDefault = $publishedByDefault;

		$this->_generatorView->isLogged = $this->_addLinks;
		$this->_generatorView->commentsBlockName = str_replace(" ", "-",$containerName);
		$this->_generatorView->websiteUrl = $this->_siteUrl;
		$this->_generatorView->containerId = $containerData['id_container'];
		$this->_generatorView->commentsArray = $commentsArray;
		//return $this->_generatorView->render('comments.phtml');

		$translator = new RCMS_Object_Parser_Translator($this->_languageId);
		$comments = $translator->processScreen($this->_generatorView->render('comments.phtml'));
		return $comments;
	}



	/**
	 * Generate new item varriable
	 *
	 * @param string $newsTitle
	 * @param array $options
	 * @param array $newsData
	 * @return string
	 */
	public function generateNewsItem($newsTitle, $options, $newsData) {
		$date= '';
		$newsItemObj = '';
		if(!empty ($newsTitle)) {
			$newsItemObj = $this->_model->selectNewsByTitle(trim($newsTitle));
			if($newsItemObj) {
				$date = $this->processNewsDate($newsItemObj->newsLastUpdate);
			}
		}
		else //process varible newsitem
		{
			if($newsData['requestedNewsPage'] != 'index.html') {
				$requestedNewsPage = explode('.', trim($newsData['requestedNewsPage']));
				$newsItemObj = $this->_model->selectNewsByUrl($requestedNewsPage[0]);
				if($newsItemObj) {
					$date = $this->processNewsDate($newsItemObj->newsDate);
				}
			}
		}
		$this->_generatorView->siteUrl = $this->_siteUrl;
		$this->_generatorView->newsItemObj = $newsItemObj;
		$this->_generatorView->date = $date;
		return $this->_generatorView->render('newsitem.phtml');
	}

	public function generateNewsTitle($newsTitle, $options, $newsData) {
/*
		$date= '';
		$newsItemObj = '';
		if(!empty ($newsTitle)) {
			$newsItemObj = $this->_model->selectNewsByTitle(trim($newsTitle));
			if($newsItemObj) {
				$date = $this->processNewsDate($newsItemObj->newsLastUpdate);
			}
		}
		else //process varible newsitem
		{
			if($newsData['requestedNewsPage'] != 'index.html') {
				$requestedNewsPage = explode('.', trim($newsData['requestedNewsPage']));
				$newsItemObj = $this->_model->selectNewsByUrl($requestedNewsPage[0]);
				if($newsItemObj) {
					$date = $this->processNewsDate($newsItemObj->newsLastUpdate);
				}
			}
		}
		$this->_generatorView->siteUrl = $this->_siteUrl;
		$this->_generatorView->newsItemObj = $newsItemObj;
		$this->_generatorView->date = $date;
		return $this->_generatorView->render('newsitem.phtml');*/
	}

	/**
	 * Generate news list varriable content for news template
	 *
	 * @return string
	 */
	public function generateNewsList() {
		$newsCategoriesArray = $this->_model->selectAllNewsCategories();
		$newsArray = $this->_model->selectAllNews();
		foreach ($newsArray as &$news) {
			$news['newsLastUpdate'] = $this->processNewsDate($news['newsLastUpdate']);
		}
		$newsArrayWithoutCategory = $this->_model->selectAllNews(0);
		foreach ($newsArrayWithoutCategory as &$news) {
			$news['newsLastUpdate'] = $this->processNewsDate($news['newsLastUpdate']);
		}
		$this->_generatorView->newsFolder = $this->_model->getNewsFolder();
		$this->_generatorView->siteUrl = $this->_siteUrl;
		$this->_generatorView->newsCategoriesArray = $newsCategoriesArray;
		$this->_generatorView->newsArray = $newsArray;
		$this->_generatorView->newsArrayWithoutCategory = $newsArrayWithoutCategory;
		return $this->_generatorView->render('newslist.phtml');
	}

	/**
	 * Proccess and return valid news item's date
	 *
	 * @param string $newsDate
	 * @return string
	 */
	public function processNewsDate($newsDate) {
		$explodeFirst = explode(" ", $newsDate);
		$date = explode("-",$explodeFirst[0]);
		return date("F jS Y",mktime(0, 0, 0, $date[1], $date[2], $date[0]));
	}

	/**
	 * Generate image gallery content
	 *
	 * @param array $params
	 * @return string
	 */
	public function generateGallery($params) {
		$gallery = $params['name'];
		$config = unserialize(Zend_Registry::get('config'));
		$path = $config->website->website->path . $config->website->website->galleries;

		if($gallery != '' && is_dir($path . $gallery) &&
			is_dir($path . $gallery . '/thumbnails/') && file_exists($path . $gallery . '/settings.txt')) {
			$pathGallery = explode('/', $config->website->website->galleries);
			$this->_generatorView->images = RCMS_Tools_FilesystemTools::scanDir($path . $gallery . '/thumbnails/');
			$this->_generatorView->settings = explode(':', @file_get_contents($path . $gallery . '/settings.txt'));
			$this->_generatorView->pathGallery = ($pathGallery[(count($pathGallery)-1)]!=''?$pathGallery[(count($pathGallery)-1)]:'galleries');
			$this->_generatorView->galleryName = $gallery;
			$this->_generatorView->siteUrl = $this->_siteUrl;
			$this->_generatorView->isLogin = $this->_addLinks;
			return $this->_generatorView->render('gallery.phtml');
		}

		if(preg_match("/^[a-z-]{1,225}$/", $gallery)) {
			if(!is_dir($path . $gallery)) {
				RCMS_Tools_FilesystemTools::mkDir($path . $gallery);
				RCMS_Tools_FilesystemTools::mkDir($path . $gallery .'/thumbnails/');
				if(!empty($params['options'])) {
					$settings = (isset($params['options'][0]) && intval($params['options'][0])>0?$params['options'][0]:'125') . ':';
					$settings .= (isset($params['options'][1]) && $params['options'][1]==1?'1':'0') . ':';
					$settings .= (isset($params['options'][2]) && $params['options'][2]==1?'1':'0') . ':';
					$settings .= (isset($params['options'][3]) && $params['options'][3]==1?'1':'0');
					@file_put_contents($path . $gallery .'/settings.txt', $settings);
				}
				else {
					@file_put_contents($path . $gallery .'/settings.txt', '125:1:1:1');
				}
				$pathGallery = explode('/', $config->website->website->galleries);
				$this->_generatorView->images = RCMS_Tools_FilesystemTools::scanDir($path . $gallery . '/thumbnails/');
				$this->_generatorView->settings = explode(':', @file_get_contents($path . $gallery . '/settings.txt'));
				$this->_generatorView->pathGallery = ($pathGallery[(count($pathGallery)-1)]!=''?$pathGallery[(count($pathGallery)-1)]:'galleries');
				$this->_generatorView->galleryName = $gallery;
				$this->_generatorView->siteUrl = $this->_siteUrl;
				$this->_generatorView->isLogin = $this->_addLinks;
				return $this->_generatorView->render('gallery.phtml');
			}
		}
		return '';
	}

	/**
	 * Regenerate news routes xml file according to the news folder recived from seosamba
	 *
	 */
	public function generateNewsRoutes() {
		$this->_generatorView->newsFolder = $this->_model->getNewsFolder();
		$config = unserialize(Zend_Registry::get('config'));
		$parsedSiteUrl = parse_url($config->website->website->url);
		$this->_generatorView->siteDir = ($parsedSiteUrl['path'] == '/') ? '' : rtrim($parsedSiteUrl['path'], '/');
		$routesContent = $this->_generatorView->render('routes.phtml');
		RCMS_Tools_FilesystemTools::saveFile(APPLICATION_PATH . '/configs/routesext.xml', $routesContent);
	}

	/**
	 * Generate captch for comments block
	 *
	 * @return string
	 */
	public function generateCaptcha() {
		$captcha = new Zend_Captcha_Image();
		$captcha->setTimeout('300')
			->setWordLen('5')
			->setHeight('60')
			->setFont($this->_sitePath.'public/system/fonts/Goulong.ttf')
			->setImgDir($this->_sitePath.'public/tmp');
		$captcha->setFontSize(35);
		$captcha->setDotNoiseLevel(0);
		$captcha->setLineNoiseLevel(0);
		//$captcha->setStartImage();
		$captcha->generate();    //command to generate session + create image
		return $captcha->getId();   //returns the ID given to session &amp; image
	}

	/**
	 * Generates paypal button form
	 *
	 * @param array $params
	 * @return string
	 */
	public function generateFormPayPal($params) {
		if(empty($params) || intval($params['name']) < 0 || count($params['options']) < 4) {
			return '' ;
		}

		$email = $this->_model->selectConfigGetEmailAdmin();
		$this->_generatorView->email = $email['admin_email']['value'];
		$this->_generatorView->price = $params['name'];
		$this->_generatorView->option1 = $params['options'][0];
		$this->_generatorView->value1 = $params['options'][1];
		$this->_generatorView->option2 = $params['options'][2];
		$this->_generatorView->value2 = $params['options'][3];
		return $this->_generatorView->render('paypalbutton.phtml');
	}

	/**
	 * Generates custom payment button content
	 *
	 * @param array $params
	 * @return string
	 */
	public function generatePaymentButton($params) {
		if(empty($params) || intval($params['name'])) {
			return '' ;
		}

		if(preg_match("/^[a-zA-Z0-9_-]{1,225}$/", $params['name'])) {
			$data = $this->_model->selectPaymentButtonByName($params['name']);
			if(is_array($data) && isset($data[0]['value']) && $data[0]['value'] != '') {
				return $data[0]['value'];
			} else {
				return '';
			}
		}
		return '';
	}

	/**
	 * Try to find content for unknown varriable
	 *
	 * @param string $variableName
	 * @return string
	 */
	public function generateUnknown($variableName) {
		return $this->_model->getVariableCode($variableName);
	}

	/**
	 * Generates news scroller content
	 *
	 * @return string
	 */
	public function generateNewsScroller() {
		$this->_generatorView->newsList = $this->_model->selectNewsItemsForScroller();
		$this->_generatorView->newsFolder = $this->_model->getNewsFolder();
		$this->_generatorView->websiteUrl = $this->_siteUrl;
		return $this->_generatorView->render('newsscroller.phtml');
	}

	/**
	 * Generate a correct rss feed link
	 *
	 * @param array $containerParams
	 * @return string
	 */
	public function generateRssFeedLink($containerParams) {
		$this->_generatorView->websiteUrl = $this->_siteUrl;
		$this->_generatorView->rssFeedName = $containerParams['name'];
		return $this->_generatorView->render('rsslink.phtml');
	}

	/**
	 * Generates custom user form
	 *
	 * @param string $containerName
	 * @param array $options
	 * @param array $pageData
	 * @return string
	 */
	public function generateForm($containerName, $options, $pageData) {
		$captchaId = '';
		if(!empty($options)) {
			if(isset($options[0]) && $options[0]=='captcha') {
				$captchaId = $this->generateCaptcha();
			}
		}
		$formObj = null;
		$formId = $this->_model->getFormId($containerName);
		$replacedContent = '';
		if($formId) {
			$formObj = new RCMS_Object_Form_Form($formId);
			$pageObj = new RCMS_Object_Page_Page($pageData['id']);
			$replacedContent .= "<form name='".$formObj->getName()."' id='".$formObj->getName()."' action='".$this->_siteUrl."sys/backend_ajax/formhandler' method='POST'>";
			if($formObj!=null &&$formObj->getCode()!=null) {
				$replacedContent .= $formObj->getCode();
			}
			$replacedContent .= "<input type='hidden' name='pageId' value='".$pageObj->getId()."'>";
			$replacedContent .= "<input type='hidden' name='formId' value='".$formObj->getId()."'>";
			if($captchaId != '') {
				$replacedContent .= "<input type='hidden' name='captchaId' value='".$captchaId."'>";
				$replacedContent .= "<img alt='' src='".$this->_siteUrl."tmp/".$captchaId.".png' id='captcha-image' style='border: medium none ; width: 200px;'/>";
				$replacedContent .= "<p><label>Enter the string above.</label></p>";
				$replacedContent .= "<p><input type='text' id='captcha-input' name='captcha[input]'/></p>";
			}
			$replacedContent .= "<p><input class='formsubmit' type='submit' value='Submit Form' /></p>";
			$replacedContent .= "</form>";
		}
		if($this->_addLinks) {
			if($formObj === null || !$formObj) {
				$replacedContent = '<a style="display:block;" href="' . $this->_siteUrl . 'sys/backend_form/addform/name/'.$containerName.'/pageId/'.$pageData['id'].'/?TB_iframe=true&height=600&width=600" class="thickbox generator-links" title="Edit form properties">Edit form properties</a>';
			}
			else {
				$replacedContent .= '<span style="display:block;"><a href="' . $this->_siteUrl . 'sys/backend_form/editform/formId/'.$formObj->getId().'/pageId/'.$pageData['id'].'/?TB_iframe=true&height=600&width=600" class="thickbox generator-links" title="Edit form properties">Edit form properties</a>/<a href="' . $this->_siteUrl . 'sys/backend_form/deleteform/formId/'.$formObj->getId().'/pageId/'.$pageData['id'].'/?TB_iframe=true&height=600&width=600" onclick="return confirm(\'Do you really want to delete this form?\');" title="Delete this form">Delete Form</a></span>';
			}
		}
		return $replacedContent;
	}

	/**
	 * Generates main menu based on accordion
	 *
	 * @return string
	 */
	public function generateMainMenuAccordion($takeDraft = true) {
		$categories = $this->_model->getMainMenuCategories($takeDraft);
		foreach($categories as $key => $category) {
			$categories[$key]['pages'] = $this->_model->getMainMenuCategoryPages($category['categoryId']);
		}
		$this->_generatorView->sitePages = $categories;
		return $this->_generatorView->render('mainmenuaccordion.phtml');
	}

	/**
	 * Generates seo top and seo bottom variables.
	 *
	 * @param string $pageId
	 * @param string $topOrButtom
	 * @return string
	 */
	public function generateSeoVar($pageId, $topOrButtom) {
		$result = '';
		switch ($topOrButtom) {
			case self::SEOVAR_TOP:
				$result = $this->_model->getSeoTopVar($pageId);
				break;
			case self::SEOVAR_BOTTOM:
				$result = $this->_model->getSeoBottomVar($pageId);
				break;
		}
		return $result;
	}

	/**
	 * Generates file neede for pr scultpting.
	 * File contains json-encoded array ([page_id] => [page_url])
	 *
	 * @param string $path
	 * @param array $data
	 * @return string
	 */
	public function generatePRSFile($path, $data) {
		return RCMS_Tools_FilesystemTools::saveFile($path . RCMS_Object_Parser_SeoParser::PFS_FILE_NAME, json_encode($data));
	}


	/**
	 * Generate Search Form
	 *
	 * Shows Search Form
	 *
	 * @param array $pageData
	 * @return string
	 */
	public function generateSearchForm($pageId) {
		if($pageId>0) {
			$pageObj = new RCMS_Object_Page_Page($pageId);
			$this->_generatorView->websiteUrl = $this->_siteUrl;
			$this->_generatorView->pageUrl = str_replace(".html", "", $pageObj->getUrl()).".html";
			return $this->_generatorView->render('searchform.phtml');
		}else {
			return "";
		}
	}

	/**
	 * Generate Search Result list
	 *
	 * @param array $searchResult
	 * @return string
	 */
	public function generateSearchResult($searchResult) {
		$pageArray = null;
		$realIdsArray = array();

		if($searchResult) {
			foreach ($searchResult as $key=>$value) {
				if(!in_array($value, $realIdsArray))
					$realIdsArray[] = $value;
			}

			foreach ($realIdsArray as $pageId) {
				$pageArray[] = new RCMS_Object_Page_Page($pageId);
			}
		}

		$this->_generatorView->pageArray = $pageArray;
		return $this->_generatorView->render('searchresult.phtml');
	}

	/**
	 * Generate Search Result list with page preview image
	 *
	 * @param array $searchResult
	 * @return string
	 */
	public function generateSearchResultImg($searchResult) {
		$pageArray = null;
		$realIdsArray = array();

		if($searchResult) {
			foreach ($searchResult as $key=>$value) {
				if(!in_array($value, $realIdsArray))
					$realIdsArray[] = $value;
			}

			foreach ($realIdsArray as $pageId) {
				$pageArray[] = $this->_model->selectPageWithImageByPageId($pageId);
			}
		}
		$this->_generatorView->pageArray = $pageArray;
		return $this->_generatorView->render('searchresultimg.phtml');
	}

	/**
	 * Generate plugin
	 *
	 * @param string $name
	 * @param array $options
	 * @param array $pageData
	 * @return string
	 */
	public function generatePluginContent($name, $options, $pageData) {
		$name = strtolower($name);
		if($name) {
			$plugin = $this->_model->selectPluginByName($name);
			if($plugin) {
				if($plugin->status != 'enabled') {
					return '';
				}
				if(file_exists('../public/plugins/'.$name.'/'.ucfirst($name).'.php') ) {
					require_once '../public/plugins/'.$name.'/'.ucfirst($name).'.php';
					$class = ucfirst($name);
					$pluginObj = new $class($options,$pageData);
					return $pluginObj->run();
				} else {
					return 'Check the file set of ' . $name . ' plugin folder.';
				}
			}
		} else {
			return '';
		}
	}

	public function generateSwapper($params, $id) {
		if (empty($params) || !isset($params['name']) || !is_array($params['options'])) {
			return '' ;
		}
		$folder = trim($params['name']);
		$pathFolder = $this->_sitePath . 'public/images/' . $folder . '/';
		if ($folder === '' || !is_dir($pathFolder) || !is_dir($pathFolder . 'original/')) {
			return '';
		}
		$this->_generatorView->folder = $folder;
		$this->_generatorView->slideshow = (isset($params['options'][0])?intval($params['options'][0]):1);
		$this->_generatorView->time = (isset($params['options'][1])?intval($params['options'][1])*1000:2000);

		$width = $params['options'][2];

		//d($params['options'],false);
		if(isset($params['options'][3])) {
			$height = $params['options'][3];
		}else {
			if(isset($params['options'][2])){
			$height = $params['options'][2];
			}else{
				$height = $width;
			}
		}

		$this->_generatorView->desiredWidth = $width;
		$this->_generatorView->desiredHeight = $height;
		$imgPresets = $this->_model->getConfigImagesPresets();
		if($width > 0 && $width <= $imgPresets['small']) {
			$this->_generatorView->sourceFolder = '/small/';
			$this->_generatorView->images = RCMS_Tools_FilesystemTools::scanDir($pathFolder . 'small/');
		}
		elseif($width >= $imgPresets['small'] && $width <= $imgPresets['medium']) {
			$this->_generatorView->sourceFolder = '/medium/';
			$this->_generatorView->images = RCMS_Tools_FilesystemTools::scanDir($pathFolder . 'medium/');
		}
		elseif($width >= $imgPresets['medium'] && $width <= $imgPresets['large']) {
			$this->_generatorView->sourceFolder = '/large/';
			$this->_generatorView->images = RCMS_Tools_FilesystemTools::scanDir($pathFolder . 'large/');
		}
		elseif($width >= $imgPresets['large'] || $width == 0) {
			$this->_generatorView->sourceFolder = '/original/';
			$this->_generatorView->images = RCMS_Tools_FilesystemTools::scanDir($pathFolder . 'original/');
		}
		//$this->_generatorView->images = RCMS_Tools_FilesystemTools::scanDir($pathFolder . 'original/');
		$this->_generatorView->uniqueId = $id;
		$this->_generatorView->url = $this->_siteUrl;
		return $this->_generatorView->render('swapper.phtml');
	}

	public function generateRegularNewsList($name, $options, $data) {
		$this->_generatorView->newsFolder = $this->_model->getNewsFolder();
		$this->_generatorView->siteUrl = $this->_siteUrl;
		$newsCategoriesArray = $this->_model->selectAllNewsCategories();
		$newsArray = $this->_model->selectAllNews();
		$newsArrayWithoutCategory = $this->_model->selectAllNews(0);
		switch($name) {
			case 'all':
				foreach ($newsArray as &$news) {
					$news['newsDate'] = $this->processNewsDate($news['newsDate']);
				}
				foreach ($newsArrayWithoutCategory as &$news) {
					$news['newsDate'] = $this->processNewsDate($news['newsDate']);
				}
				$this->_generatorView->newsCategoriesArray = $newsCategoriesArray;
				$this->_generatorView->newsArray = $newsArray;
				$this->_generatorView->newsArrayWithoutCategory = $newsArrayWithoutCategory;
				return $this->_generatorView->render('newslist.phtml');
				break;
			case 'archived':
				$archivedNews = array();
				foreach ($newsArray as $newsItem) {
					if($newsItem['newsArchived']) {
						$archivedNews[] = $newsItem;
					}
				}
				$this->_generatorView->news = $archivedNews;
				return $this->_generatorView->render('newslistarchived.phtml');
				break;
			default:
				$catId = 0;
				foreach ($newsCategoriesArray as $newsCatItem) {
					if($newsCatItem['newsCategoryName'] == $name) {
						$this->_generatorView->categoryName = $name;
						$catId = $newsCatItem['newsCategoryId'];
						break;
					}
				}
				$this->_generatorView->categoryNews = $this->_model->selectAllNews($catId);
				return $this->_generatorView->render('newslistbycat.phtml');
				break;
		}
	}

	public function generateNewsFolderUrl() {
		$result = $this->_model->selectDefaultNewsFolder();
		if($result && !empty($result['default_news_folder'])) {
			return $this->_siteUrl.$result['default_news_folder']."/";
		}else {
			return $this->_siteUrl."news/";
		}
	}

	/**
	 * Generates list of pages for given category name
	 *
	 * If there is no category with such name returns false
	 * If there are no pages in the category returns empty array
	 *
	 * @param string $categoryName
	 * @param boolean $withImg tells generator that result should include pages thumbnails
	 */
	public function generateListPages($categoryName, $withImg) {

		if(is_array($withImg) && isset($withImg[0])) {
			$withImg = ($withImg[0] == 1) ? true : false;
		}
		elseif($withImg !== true) {
			$withImg = false;
		}
		$categoryId = $this->_model->getCategoryIdByName($categoryName);
		if(!$categoryId) {
			return 'There is no category with such name: '. $categoryName . '!';
		}
		if($withImg) {
			$pages = $this->_model->getCategoryPagesListImg($categoryId);
			$this->_generatorView->categoryPagesListImg = $pages;
			return $this->_generatorView->render('catpageslistimg.phtml');
		}
		else {
			$pages = $this->_model->getCategoryPagesList($categoryId);
			$this->_generatorView->categoryPagesList = $pages;
			return $this->_generatorView->render('catpageslist.phtml');
		}

	}

	/**
	 * Generate new item varriable
	 *
	 * @param string $newsTitle
	 * @param array $options
	 * @param array $newsData
	 * @return string
	 */
	public function generateSocialBookmarksBlock($pageData) {
	//$pageUrl,
		$pageTitle = $pageData['header_title'];
		$websiteUrl = $pageData['websiteUrl'];
		$pageUrl = $websiteUrl.$pageData['url'].".html";
		//d($pageUrl);

		$this->_generatorView->pageTitle = $pageTitle;
		$this->_generatorView->websiteUrl = $websiteUrl;
		$this->_generatorView->pageUrl = $pageUrl;
		return $this->_generatorView->render('socialmarks.phtml');
	}

	function generateNewsAggregatorBlock($pageData) {
		$websiteUrl = $pageData['websiteUrl'];
		$xmlFilesArray = RCMS_Tools_FilesystemTools::findFilesByExt('../public', 'xml');
		if(in_array('all.xml', $xmlFilesArray)) {
			$rssUrl = $websiteUrl.RCMS_Object_QuickConfig_QuickConfig::$allNewsXmlName.'.xml';
			$this->_generatorView->rssUrl = $rssUrl;
			return $this->_generatorView->render('newsaggregator.phtml');
		}
		else {
			return '';
		}
	}

	public function cutDescription($string,$length=200) {
		$string = trim($string);
		if(!empty($string)) {
			$str = substr($string, 0,$length-3);
			$len = strlen($str);
			if($str[$len-1]!=' ') {
				$arrTmp = explode(" ",$str);
				$size = sizeof($arrTmp);
				$replace = $arrTmp[$size-1];
				return str_replace($replace, '', $str).' ...';
			}
			return $str.' ...';
		}
		return '';
	}

	public function processNewsRssDate($date) {
		$tmp = explode(" ",$date);
		return $tmp[0]." ".$tmp[1]." ".$tmp[2]." ".$tmp[3];
	}

	public function processAtomRssDate($date) {
		$tmp = explode("-",$date);
		$year = $tmp[0];
		$month = $tmp[1];
		$day = substr($tmp[2], 0,2);
		$resDate = date("D, j M Y",mktime(0, 0, 0, $month, $day, $year));
		return $resDate;
	}

	public function generateExternalRSS($url, $options,$data) {
		$newsRss = array();
		$atomRss = array();
		$calendarRss = array();
		$countResult =  intval($options[0]);
		$maxCharacters  = (isset($options[1]))?trim($options[1]):'';
		$showFullDescription = false;

		if(!intval($maxCharacters)) {
			$showFullDescription = true;
		}
		if(!$countResult) {
			$countResult = 4;
		}

		if(trim($url)=='' || !$url) {
			return '';
		}



		$result = $this->sendRssCURL($url);

		$xml = simplexml_load_string($result);
		$data = get_object_vars($xml);

		if(!strstr($url, "calendar")) {
		//regular news rss
			if($xml->channel) {
				foreach ($xml->channel as $key=>$value) {
					$tmp = get_object_vars($value);
					if(!$tmp['item']->title) {
						$newsRss = $tmp['item'];
					}else {
						$newsRss[0] = $tmp['item'];
					}
				}
			}

			if($newsRss) {
				if(!$showFullDescription) {
					foreach ($newsRss as &$item) {
						$item->description = $this->cutDescription(strip_tags($item->description),$maxCharacters);
					}
				}

				foreach ($newsRss as &$item) {
					$item->pubDate = $this->processNewsRssDate($item->pubDate);
				}

			}

			//atomRSS
			if($data['entry']) {
				foreach ($data['entry'] as $entry) {
					$pubDate = $this->processAtomRssDate(current($entry->published));
					$link = current($entry->link);
					$content = strip_tags($entry->content);
					if(!$showFullDescription) {
						$content = $this->cutDescription($content,$maxCharacters);
					}
					$atomRss[] = array(
						"title"=>end($entry->title),
						"link"=>$link['href'],
						"content"=>$content,
						"pubDate"=>$pubDate
					);
				}
			}
		}
		else {
			foreach ($data['entry'] as $entry) {

				$title = end($entry->title);
				if(strlen($title['type'])==1) {
				//d($data);
					$content = strip_tags($entry->content);
					$tmp = explode("\n", $content);
					$eventDate = $tmp[0];
					$where = $tmp[3];
					$content = $tmp[5];
					if(!$showFullDescription) {
						$content = $this->cutDescription($content,$maxCharacters);
					}
					$link = current($entry->link);
					$link = $link['href'];

					$calendarRss[]=array(
						"title"=>$title,
						"eventDate"=>$eventDate,
						"where"=>$where,
						"description"=>$content,
						"link"=>$link,
						"content"=>$entry->content
					);
				}
			}
		}

		$this->_generatorView->countResult = $countResult;
		$this->_generatorView->newsRss = $newsRss;
		$this->_generatorView->atomRss = $atomRss;
		$this->_generatorView->calendarRss = $calendarRss;
		return $this->_generatorView->render('xrss.phtml');
	}

	public function sendRssCURL($url) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,html_entity_decode($url));
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_FAILONERROR, true);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_REFERER, "www.seotoaster.com");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		//curl_setopt($ch, CURLOPT_POST, 'application/x-www-form-urlencoded');
		/*curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);*/
		$result = curl_exec($ch);
		curl_close($ch);
		return $result;
	}

    public function generateProductContent($id, $preview = false)
    {
        if ($id <= 0 ) {
            return '';
        }
        $product = new RCMS_Object_Product_Product($id);
        if ($product->getId() > 0) {
            return $this->_generateTemplateForProduct($product, $preview);
        }
        return '';
    }

    public function generateProductListContent($params)
    {
        /* generate string of query where parameters separates the symbol ':' */
        $str = '';
        if (isset($params['name'])) {
            $str .= trim($params['name']);
        }
        if (isset($params['options']) && count($params['options']) > 0) {
            if ($str == '') {
                $str .= implode(':', $params['options']);
            } else {
                $str .= ':'.implode(':', $params['options']);
            }
        }
        if ($str == '') {
            return '';
        }
        /* obtain an array of parameters */
        $data = explode(':', $str);
        $order = array();
        $brands = array();
        $categories = array();
        
        /* parse parameters */
        foreach ($data as $d) {
            $options =  explode('-', trim($d,','));
            if (!isset($options[0]) || !isset($options[1])) {
                continue;
            }
            switch (trim($options[0])) {
                case 'order':
                    $tmp = explode(',', trim($options[1]));
                    if (count($tmp) > 0) {
                        foreach ($tmp as $tmpVal) {
                            $tmpVal = trim($tmpVal);
                            if ($tmpVal == 'name' || $tmpVal == 'brand' || $tmpVal == 'price') {
                                $order[] = $tmpVal;
                            }
                        }
                    }
                    break;
                case 'brands':
                    $tmp = explode(',', trim($options[1]));
                    if (count($tmp) > 0) {
                        $brands = $tmp;
                    }
                    break;
                case 'categories':
                    $tmp = explode(',', trim($options[1]));
                    if (count($tmp) > 0) {
                        $categories = $tmp;
                    }
                    break;
                default:
                    break;
            }
        }
        $products = array();
        
        /* if we don't have categories, we got products by brand */
        if (count($categories) == 0) {
            if (count($brands) > 0) {
                foreach ($brands as $brand) {
                    $brand = trim($brand);
                    if ($brand == '') {
                        continue;
                    }
                    $result = $this->_model->selectProductsByBrandName($brand);
                    if (is_array($result) && count($result) > 0 ) {
                        $products = array_merge($products, $result);
                    }
                }
            }
        } else {
            if (count($categories) > 0) {
                foreach ($categories as $category) {
                    $category = intval($category);
                    if ($category <= 0) {
                        continue;
                    }
                    $result = $this->_model->selectProductsByGroupId($category);
                    if (is_array($result) && count($result) > 0 ) {
                        $products = array_merge($products, $result);
                    }
                }
                /* filter by brand */
                if (count($brands) > 0 && count($products) > 0) {
                    $tmp = array();
                    foreach ($products as $prod) {
                        if (in_array($prod['brand'], $brands)) {
                            $tmp[] = $prod;
                        }
                    }
                    if (count($tmp) > 0) {
                        $products = $tmp;
                    }
                }
            }
        }
        
        /* removes duplicate a product */
        $tmp = $products;
        foreach ($products as $key1 => $val1) {
            $c = 0;
            foreach ($tmp as $key2 => $val2) {
                if ($val1['id'] == $val2['id']) {
                    $c++;
                    if ($c >= 2) {
                        unset($products[$key1]);
                        unset($tmp[$key2]);
                    }
                }
            }
        }
        
        if (count($products) <= 0) {
            return '';
        }
        
        /* make arrays for sorting */
        $price = $brand = $name = array();
        foreach ($products as $dataProduct) {
           $brand[] = $dataProduct['brand'];
           $price[] = $dataProduct['price'];
           $name[] = $dataProduct['name'];
        }
        
        /* sorting */
        $countOrder = count($order);
        switch ($countOrder) {
            case '1':
                array_multisort($$order[0], $products);
                break;
            case '2':
                array_multisort($$order[0], $$order[1], $products);
                break;
            case '3':
                array_multisort($$order[0], $$order[1], $$order[2],$products);
                break;
            default:
                sort($products);
                break;
        }
        
        /* generate the content for list product */
        $content = '';
        foreach ($products as $item) {
            $product = new RCMS_Object_Product_Product($item['id']);
            $content .= $this->_generateTemplateForProduct($product);
            unset ($product);
        }
        return $content;
    }

    private function _generateTemplateForProduct(RCMS_Object_Product_Product $product, $preview = false)
    {
        $template = '';
        $result = false;

        if ($preview) {
            $result = $this->_model->selectTemplateForProduct('template_product');
            if (is_array($result) && isset($result['template_product']['value'])) {
                $template = $result['template_product']['value'];
            }
        } else {
            $result = $this->_model->selectTemplateForProduct('template_prod_list');
            if (is_array($result) && isset($result['template_prod_list']['value'])) {
                $template = $result['template_prod_list']['value'];
            }
        }
        if ($template == '') {
            return '';
        }
        $currency = $result['currency']['value'];

        /* got categories */
        $categories = '';
        foreach ($product->getGroups() as $group) {
            $categories .= $group['name'].', ';
        }
        $categories = rtrim($categories, ', ');
        /* got related */
        $related = '';
        $relateds = explode(',', $product->getRelated());
        foreach ($relateds as $id) {
            $productRelated = new RCMS_Object_Product_Product($id);
            if ($productRelated->getId() > 0) {
                if ($productRelated->getPageId() > 0) {
                    $pageProduct = new RCMS_Object_Page_Page($productRelated->getPageId());
                     if ($pageProduct->getId() > 0 && $pageProduct->getUrl() != '') {
                        $related .= '<a href="'.$this->_siteUrl.$pageProduct->getUrl().'.html">'.$productRelated->getName().'</a>, ';
                     } else {
                        $related .= $productRelated->getName().', ';
                     }
                     unset ($pageProduct);
                } else {
                    $related .= $productRelated->getName().', ';
                }
            }
            unset ($productRelated);
        }
        $related = rtrim($related, ', ');
        /* got options */
        $options = explode('###', $product->getOptions());
        if (trim($options[count($options)-1]) == '') {
            unset ($options[count($options)-1]);
        }
        $optionsContent = '';
        if (count($options) > 0) {
            foreach ($options as $option) {
                $option = str_replace(':::', ' : ', $option);
                $optionsContent .= '<span class="option">'.$option.'</span>';
            }
        }
        /* link to page */
        $link = '';
        $page = new RCMS_Object_Page_Page($product->getPageId());
        if ($page->getId() > 0 && $page->getUrl() != '') {
            $link = $this->_siteUrl.trim($page->getUrl()).'.html';
        }
        unset ($page);

        /* button 'addtocart' */
        $translator = new RCMS_Object_Parser_Translator($this->_languageId);
        $addtocart = $translator->processScreen('<form action="javascript:;"><input type="button" class="addtocart" value="{%Add to Cart%}" onclick="addToCart(\''.$product->getId().'\');"></form>');

        /* link to original of image */
        $zoomImage =  str_replace('/small/', '/original/', $this->_siteUrl.$product->getPhoto());

        /* link for edit product */
        $linkToEditProduct = '';
        if ($this->_addLinks) {
            $linkToEditProduct = '<a href="javascript:;" class="linktoeditproduct" onclick="tb_show(\'\',\''.$this->_siteUrl.'sys/backend_shopping/product/id/'.$product->getId().'/?TB_iframe=true&height=525&width=845\',\'\');">Edit this product</a>';
        }

        /* photo of product */
        $photo = '';
        if ($preview) {
            $photo = $this->_siteUrl.str_replace('/small/', '/medium/', $product->getPhoto());
        } else {
            $photo = $this->_siteUrl.$product->getPhoto();
        }

        /* parser variables */
        $template = str_replace('{brand}', $product->getBrand(), $template);
        $template = str_replace('{categories}', $categories, $template);
        $template = str_replace('{photo}', $photo, $template);
        $template = str_replace('{itemid}', $product->getItemId(), $template);
        $template = str_replace('{price}',$product->getPrice() .' '.$currency, $template);
        $template = str_replace('{name}', $product->getName(), $template);
        $template = str_replace('{description}', nl2br($product->getDescription()), $template);
        $template = str_replace('{related}', $related, $template);
        $template = str_replace('{options}', $this->_generateOptionsContent($options, $product->getId()), $template);
        $template = str_replace('{url}', $link, $template);
        $template = str_replace('{addtocart}', $addtocart, $template);
        $template = str_replace('{zoomimage}', $zoomImage, $template);
        $template = str_replace('{editproduct}', $linkToEditProduct, $template);
        return $template;
    }

	private function _generateOptionsContent($options, $productId) {
		$forSelects  = array();
		$htmlContent = '';
		foreach ($options as $key => $option) {
			$explodedOption = explode(':::', $option);
			$forSelects[$key]['label']   = trim($explodedOption[0]);
			$forSelects[$key]['options'] = explode(',', $explodedOption[1]);
		}
		//making html
		if(sizeof($forSelects) > 0) {
			$this->_generatorView->forSelects = $forSelects;
			$this->_generatorView->productId  = $productId;
			$content = $this->_generatorView->render('itemoptions.phtml');
			return $content;
		}
		return '';
	}

	public function generateQuoteContent(RCMS_Object_Quote_Quote $quote, RCMS_Object_Shopping_ShoppingUserCart $userCart) {
		$totalPrice = 0;
		$cartData = $userCart->getCartData();
		foreach($cartData as $key => $value) {
			$totalPrice += $value['price'] * $value['count'];
		}
		$this->_generatorView->shoppingConfigData = $this->_model->selectShoppingConfig();
		$this->_generatorView->userName   = $userCart->getName();
		$this->_generatorView->userEmail  = $userCart->getEmail();
		$this->_generatorView->totalPrice = $totalPrice;
		$this->_generatorView->quoteName  = $quote->getName();
		$this->_generatorView->cartData   = $userCart->getCartData();
		return $this->_generatorView->render('quote.phtml');
	}

	public function generateQuoteMailToUser($quoteId, $userName) {
		$this->_generatorView->userName = $userName;
		$this->_generatorView->qid = $quoteId;
		$this->_generatorView->websiteUrl = $this->_siteUrl;
		return $this->_generatorView->render('quotemailtouser.phtml');
	}

	/**
	 * Generate cart widget which shows how many items in user's shopping cart
	 *
	 */
	public function generateCartWidget() {
		$shoppingCart = new RCMS_Object_Shopping_ShoppingCart();
		$this->_generatorView->itemsCount = $shoppingCart->getItemsCountForCart();
		$this->_generatorView->totalPrice = $shoppingCart->getTotalPrice();

		$translator = new RCMS_Object_Parser_Translator($this->_languageId);
		return $translator->processScreen($this->_generatorView->render('cart.phtml'));
	}

	public function generateConcatCss($pageData) {
		if(file_exists($pageData['templateTheme'] . '/concat.css')) {
			return true;
		}
		return RCMS_Tools_Tools::createConcatCss($pageData['templateTheme']);
	}
}